package cj.utils;

import java.util.Arrays;

/**
 * 握手验证算法
 * @author Administrator
 *
 */
public class SignKeyUtil {
	
	public static void main(String[] args) throws Exception
	{
		String printNo = "8150211033";
		String orderNo = "OS20160229142724259";
		String cardNo = "8027110115021103";
		String signkey = "82a54e889c004e3fadda170cf1bf8290";
		String sign = "927EC96C8AB92F39347C9F1EB11B4F9B";
		boolean flag = invokeCardSignKey(printNo, orderNo, cardNo, signkey,sign);
		System.out.println(flag);
		System.out.println(returnSignMd5(printNo, orderNo, cardNo, signkey));
	}
	
	/**
	 * 调用验证加密是否通过
	 * @param printNo	刻印号
	 * @param orderNo	订单编号
	 * @param cardNo	内部芯片逻辑号
	 * @param signkey	给出的加密Key
	 * @param sign		传递过来的sign
	 * @return	true/false
	 * @throws Exception
	 */
	public static Boolean invokeCardSignKey(String printNo,String orderNo,String cardNo,String signkey,String sign) throws Exception
	{
		//step1-4
		String sign_md5 =returnSignMd5(printNo, orderNo, cardNo, signkey);
		
		//step5-----判断 sign_md5 后的密文是否与传入的 sign 相同
		if(sign_md5.equals(sign))
		{
			return Boolean.TRUE;
		}
		else
		{
			return Boolean.FALSE;
		}
	}
	
	/**
	 * 返回加密sign_md5后的内容
	 * @param printNo
	 * @param orderNo
	 * @param cardNo
	 * @param signkey
	 * @return
	 * @throws Exception
	 */
	public static String returnSignMd5(String printNo,String orderNo,String cardNo,String signkey) throws Exception
	{
		//step1-----拼接字符串，key value 形式
		String print_No="printNo="+printNo;
		String order_No="orderNo="+orderNo;
		String card_No="cardNo="+cardNo;
		
		String[] arr = new String[] { print_No, order_No, card_No};
		//step2-----将print_No、order_No、card_No三个参数进行字典排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]+"&");
		}
		//step3-----将 signkey=xxx 加入最末位
		String ss = content+"signkey="+signkey;
		//step4-----将拼接号的字符串，MD5加密32位
		String sign_md5 = MD5Security.md5(ss);
//		System.out.println("sign----"+sign_md5);
		return sign_md5;
	}
}
